﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using Microsoft.VisualStudio.TestTools.UnitTesting;

using System.Collections.Generic;
using System.Linq;
using ScrumTable.Common.Collections;
using ScrumTable.Common.Monitoring;
using ScrumTable.Common.Security;
using ScrumTable.DL.Data.Common;
using ScrumTable.DL.Data.Generic.Test;
using ScrumTable.DL.Data.Generic.Test.Mocks;
using ScrumTable.DL.Data.Generic.Test.Mocks.Config.Driver;
using ScrumTable.DL.Data.Generic.Test.Mocks.Config.Schema;
using ScrumTable.DL.Data.Local.Config.Driver;
using ScrumTable.DL.Data.Local.Config.Schema;
using ScrumTable.DL.Data.Schema;

#endregion

namespace ScrumTable.DL.Data.Local.Test
{
    /// <summary>
    /// This is the test class for Local.DataContext class.
    /// </summary>
    [TestClass]
    public class DataContextTest
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private DataContext _context;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext { get; set; }

        #endregion

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new DataContextTest instance.
        /// </summary>
        public DataContextTest()
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Use TestInitialize to run code before running each test .
        /// </summary>
        [TestInitialize]
        public void TestInitialize()
        {
            _context = new DataContext(new DataContextInfoStub(
                TestContext.TestDir,
                dci => new DataSchemaSelector(dci),
                dci => new DriverConfigSelector(dci)));
            _context.Connection.Connect(
                new ConnectionInformationManager(ConnectionInformation.Empty),
                result => { },
                Resources.GetProjectTestDataFilePath(TestContext.TestDir));

            _context.ImportData(Resources.FullProject2IdChain, new NullDataImportMonitor());
            _context.ImportData(Resources.FullProject1IdChain, new NullDataImportMonitor());
        }

        /// <summary>
        /// Use TestCleanup to run code after each test has run.
        /// </summary>
        [TestCleanup]
        public void TestCleanup()
        {
            _context.Dispose();
            _context = null;
        }

        [TestMethod]
        public void TestConnection()
        {
            Assert.IsNotNull(_context.Connection);
        }

        [TestMethod]
        public void TestSerializeData()
        {
            // test nullable types for serialization
            IDataObject task1 = _context.Storage[_context.Schema.TaskSchema].GetById(
                Resources.Task1IdChain,
                Resources.Task1Id);
            task1[_context.Schema.TaskSchema.RemainingWork] = new double?(task1.GetData<double>(_context.Schema.TaskSchema.RemainingWork));

            IDataObject task2 = _context.Storage[_context.Schema.TaskSchema].GetById(
                Resources.Task2IdChain,
                Resources.Task2Id);
            task2[_context.Schema.TaskSchema[TestFieldDefinitionSet.PriorityFieldName]] = new int?(); // same effect as [= null;]
            task2[_context.Schema.TaskSchema.CompletedWork] = 2.0; // value must be stored into the settings -> no server side field available
            task2[_context.Schema.TaskSchema.RemainingWork] = null;

            // serialize original data
            _context.SerializeTo(Resources.GetTestDataFilePath(TestContext.TestDir));

            // create new context and load serialized data
            DataContext context = new DataContext(new DataContextInfoStub(
                TestContext.TestDir, 
                dci => new DataSchemaSelector(dci),
                dci => new DriverConfigSelector(dci)));
            context.Connection.Connect(
                new ConnectionInformationManager(ConnectionInformation.Empty),
                result => { },
                Resources.GetTestDataFilePath(TestContext.TestDir));

            context.ImportData(new ValueChain<string>(Resources.Project2Id), new NullDataImportMonitor());
            context.ImportData(new ValueChain<string>(Resources.Project1Id), new NullDataImportMonitor());

            // check data
            CheckDataContextEqual(_context, context);
        }

        [TestMethod]
        public void TestStorage()
        {
            Assert.IsNotNull(_context.Storage);
        }


        private void CheckDataContextEqual(IDataContext originalData, IDataContext dataToCheck)
        {
            foreach (SchemaBase schema in _context.Schema.Schemata)
            {
                Assert.IsNotNull(dataToCheck.Storage[schema]);
                Assert.AreEqual(
                    originalData.Storage[schema].GetAll().Count(),
                    dataToCheck.Storage[schema].GetAll().Count() );

                CheckDataStorageEqual(dataToCheck, schema);
            }
        }

        private void CheckDataStorageEqual(IDataContext dataToCheck, SchemaBase daoSchema)
        {
            foreach (KeyValuePair<ValueChain<string>, ICollection<IDataObject>> keyObjectsPair in dataToCheck.Storage[daoSchema].GetAll())
            {
                foreach (IDataObject dataObject in keyObjectsPair.Value)
                {
                    CheckDataObjectEqual(dataToCheck, daoSchema, dataObject, keyObjectsPair.Key);
                }
            }
        }

        private void CheckDataObjectEqual(IDataContext dataToCheck, SchemaBase daoSchema, IDataObject dataObject, ValueChain<string> parentIds)
        {
            IDataObject objectToCompare = dataToCheck.Storage[daoSchema].GetById(parentIds, dataObject.Id);
            Assert.IsFalse(string.IsNullOrEmpty(objectToCompare.Id));

            foreach (SchemaBase valueSchema in daoSchema.Schemata)
            {
                if (!valueSchema.IsSchemaReference)
                {
                    Assert.AreEqual(dataObject[valueSchema], objectToCompare[valueSchema]);
                }
            }
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion
    }
}
